package Controller;

import demo.Students;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 2024/6/3 Cjj 创建HashMap集合
 *  *  键是学生对象，值是籍贯
 *  *  储存3个键值对元素，并遍历
 *  *  要求：同姓名 同年龄认为是同一个学生
 */
public class StudentController {
    public static void main(String[] args) {

        //创建学生对象
        Students s1 = new Students("小明",14);
        Students s2 = new Students("张三",18);
        Students s3 = new Students("王霞",20);

        //1.将学生对象添加到HashMap中
        HashMap<Students, Object> map = new HashMap<>();
        map.put(s1,"陕西");
        map.put(s2,"浙江");
        map.put(s3,"山东");
        System.out.println(map);

        //2.遍历集合
        //通过键寻找值遍历
        Set<Students> students = map.keySet();//将所有键存储到set中
        for (Students student : students) {//循环遍历所有键, 通过键寻找值对象
            String value = (String) map.get(student);
            System.out.println( student+"="+value);

        }

        //2.2通过键值对遍历
        Set<Map.Entry<Students, Object>> entrySet = map.entrySet();//将所有键值对放到set集合中
        for (Map.Entry<Students, Object> entry : entrySet) {
            Students key = entry.getKey();//得到键
            Object value = entry.getValue();//得到值
            System.out.println(key + "=" + value);

        }
    }
}
